package com.weixin.paleituo.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.OrderPayMoneyGridViewAdapter;
import com.weixin.paleituo.annotation.WeChatPayType;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.DepositBean;
import com.weixin.paleituo.bean.OrderBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.WeiChatPayBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.factory.ThreadFactory;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.PayResult;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.TimeReduce;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.view.MyGridView;
import com.weixin.paleituo.view.RegisterProtocolPopupWindow;
import com.weixin.paleituo.wxapi.WXPayEntry;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 订单页面
 */
public class OrdersActivity extends BaseActivity {

    @BindView(R.id.iv_back_activity_orders)
    ImageView mIvBackActivityOrders;
    @BindView(R.id.tv_time_activity_orders)
    TextView mTvTimeActivityOrders;
    @BindView(R.id.gridView_activity_orders)
    MyGridView mGridViewActivityOrders;
    @BindView(R.id.iv_weixin_activity_orders)
    ImageView mIvWeixinActivityOrders;
    @BindView(R.id.rl_weixin_activity_orders)
    RelativeLayout mRlWeixinActivityOrders;
    @BindView(R.id.iv_zhifubao_activity_orders)
    ImageView mIvZhifubaoActivityOrders;
    @BindView(R.id.rl_zhifubao_activity_orders)
    RelativeLayout mRlZhifubaoActivityOrders;
    @BindView(R.id.cb_protocol_activity_orders)
    CheckBox mCbProtocolActivityOrders;
    @BindView(R.id.tv_protocol_activity_orders)
    TextView mTvProtocolActivityOrders;
    @BindView(R.id.tv_paymoney_activity_orders)
    TextView mTvPaymoneyActivityOrders;
    @BindView(R.id.tv_order_number_activity_orders)
    TextView mTvOrderNumberActivityOrders;
    @BindView(R.id.tv_house_type_activity_orders)
    TextView mTvHouseTypeActivityOrders;
    /*    @BindView(R.id.tv_order_time_activity_orders)
        TextView mTvOrderTimeActivityOrders;*/
    @BindView(R.id.iv_icon_wx_activity_orders)
    ImageView mIvIconWxActivityOrders;
    @BindView(R.id.iv_icon_zfb_activity_orders)
    ImageView mIvIconZfbActivityOrders;
    @BindView(R.id.ll_normal_content_layout)
    LinearLayout mLlNormalContentLayout;
    @BindView(R.id.ll_notime_content_layout)
    LinearLayout mLlNotimeContentLayout;
    @BindView(R.id.iv_time_activity_order)
    ImageView mImageTime;


    private OrderPayMoneyGridViewAdapter mOrderPayMoneyGridViewAdapter;
    private boolean isWeixinPay;
    private RegisterProtocolPopupWindow mRegisterProtocolPopupWindow;
    private OrderBean mOrderBean;
    List<DepositBean> depositBeanList = new ArrayList<>();
    private TimeReduce timeReduce;
    private boolean isStopTime = false; //是否停止倒计时
    private String roomId;
    private String mMoneyStr;
    Dialog loadingDialog;
    private IWXAPI mIWXAPI;
    private String payStyle;
    private static final int SDK_PAY_FLAG = 1;
    private String mContent;
    private int type;


    @Override
    protected void initView() {
        setContentView(R.layout.activity_orders);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mGridViewActivityOrders.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtils.i(TAG, "mygrdie 的点击事件");
                mOrderPayMoneyGridViewAdapter.setSelectPosition(position);
                mOrderPayMoneyGridViewAdapter.notifyDataSetChanged();
                mMoneyStr = depositBeanList.get(position).getSum() + "";
                mTvPaymoneyActivityOrders.setText("立即支付" + mMoneyStr);

            }
        });
        mCbProtocolActivityOrders.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCbProtocolActivityOrders.setBackgroundResource(R.mipmap.choice_hook);
                } else {
                    mCbProtocolActivityOrders.setBackgroundResource(R.mipmap.choice_square);

                }

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        mLlNormalContentLayout.setVisibility(View.VISIBLE);
        mIWXAPI = WXAPIFactory.createWXAPI(this, WXPayEntry.APP_ID, true);
        boolean b = mIWXAPI.registerApp(WXPayEntry.APP_ID);
       // ToastUtils.makeText(b + "::::微信支付注册  ");
        mOrderBean = getIntent().getParcelableExtra(Contans.INTENT_DATA);
        mContent = mOrderBean.getContent();
        roomId = getIntent().getStringExtra("roomId");

        type = getIntent().getIntExtra("type",0);


        isStopTime = false;

        if (mOrderBean != null) {
            int time = mOrderBean.getTime();
            if (time>0){
                timeReduce = new TimeReduce(mTvTimeActivityOrders, time * 60, this);
                timeReduce.setTimerOverListener(new TimeReduce.TimerOver() {
                    @Override
                    public void timerOver() {
                        // finish();
                        isStopTime = true;
                        mLlNormalContentLayout.setVisibility(View.INVISIBLE);
                        mLlNotimeContentLayout.setVisibility(View.VISIBLE);
                        mImageTime.setVisibility(View.INVISIBLE);
                    }
                });
            }
            mTvOrderNumberActivityOrders.setText(mOrderBean.getOrderId() + "");
            mTvHouseTypeActivityOrders.setText(mOrderBean.getFullname() + "");
            //    mTvOrderTimeActivityOrders.setText(mOrderBean.getCreateTime()+"");
            List<DepositBean> deposit = mOrderBean.getDeposit();
            if (deposit != null && deposit.size() > 0) {
                depositBeanList.clear();
                depositBeanList.addAll(deposit);
                mMoneyStr = depositBeanList.get(0).getSum() + "";
                mTvPaymoneyActivityOrders.setText("立即支付" + mMoneyStr);
            }
            String alipay = mOrderBean.getAlipay();
            String wechat = mOrderBean.getWechat();
            if (!StringUtils.isEmpty(alipay) && alipay.equals("1")) {
                mRlZhifubaoActivityOrders.setVisibility(View.VISIBLE);
            } else {
                mRlZhifubaoActivityOrders.setVisibility(View.GONE);

            }

            if (!StringUtils.isEmpty(wechat) && wechat.equals("1")) {
                mRlWeixinActivityOrders.setVisibility(View.VISIBLE);
            } else {
                mRlWeixinActivityOrders.setVisibility(View.GONE);

            }

            if (!StringUtils.isEmpty(wechat) && wechat.equals("1")) {
                //微信
                isWeixinPay = true;
                mIvZhifubaoActivityOrders.setImageResource(R.mipmap.xe_h);
                mIvWeixinActivityOrders.setImageResource(R.mipmap.chooce_green);
            } else {
                isWeixinPay = false;
                //zhifu bao
                mIvZhifubaoActivityOrders.setImageResource(R.mipmap.chooce_green);
                mIvWeixinActivityOrders.setImageResource(R.mipmap.xe_h);

            }
        }

        mOrderPayMoneyGridViewAdapter = new OrderPayMoneyGridViewAdapter(this, depositBeanList);
        mGridViewActivityOrders.setAdapter(mOrderPayMoneyGridViewAdapter);


    }

    /**
     *
     * @param context
     * @param orderBean
     * @param checkRoomId
     * @param type   1 非遥号  2摇号
     */
    public static void startActivity(Context context, OrderBean orderBean, int checkRoomId,int type) {
        Intent intent = new Intent(context, OrdersActivity.class);
        intent.putExtra(Contans.INTENT_DATA, orderBean);
        intent.putExtra("roomId", checkRoomId + "");
        intent.putExtra("type",type);
        context.startActivity(intent);
    }


    @OnClick(R.id.iv_back_activity_orders)
    public void onMIvBackActivityOrdersClicked() {
        finish();
    }

    @OnClick(R.id.rl_weixin_activity_orders)
    public void onMRlWeixinActivityOrdersClicked() {
        mIvZhifubaoActivityOrders.setImageResource(R.mipmap.xe_h);
        mIvWeixinActivityOrders.setImageResource(R.mipmap.chooce_green);
        isWeixinPay = true;

    }

    @OnClick(R.id.rl_zhifubao_activity_orders)
    public void onMRlZhifubaoActivityOrdersClicked() {
        mIvWeixinActivityOrders.setImageResource(R.mipmap.xe_h);
        mIvZhifubaoActivityOrders.setImageResource(R.mipmap.chooce_green);
        isWeixinPay = false;
    }


    @OnClick(R.id.tv_protocol_activity_orders)
    public void onMTvProtocolActivityOrdersClicked(View view) {
        if (!StringUtils.isEmpty(mContent)){
            if (mRegisterProtocolPopupWindow == null) {
                mRegisterProtocolPopupWindow = new RegisterProtocolPopupWindow(this,mContent);
            }
            mRegisterProtocolPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        }
    }

    @OnClick(R.id.tv_paymoney_activity_orders)
    public void onMTvPaymoneyActivityOrdersClicked() {

        if (isStopTime) {
            ToastUtils.makeText("订单已失效，请重新选择");
            return;
        }
        if (!mCbProtocolActivityOrders.isChecked()) {
            ToastUtils.makeText("请同意房屋购买协议");
            return;
        }

        LogUtils.i(TAG, "roomId  ::" + roomId);
        LogUtils.i(TAG, "deposit  ::" + mMoneyStr);
        LogUtils.i(TAG, "orderid  ::" + mOrderBean.getOrderId());

        payStyle = isWeixinPay ? "2" : "1";
        if (isWeixinPay) {
            //微信
            final Observable<StatusCode<WeiChatPayBean>> weChatPayOrder = ApiUtils.getApi().getWeChatPayOrder(mOrderBean.getHousesId() + "", mMoneyStr, mOrderBean.getOrderId() + "", mOrderBean.getFullname(),type, BaseApplication.sUserInfoBean.userId,BaseApplication.sUserInfoBean.getToken())
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {

                            if (loadingDialog == null) {

                                loadingDialog = LoadingDialogUtils.createLoadingDialog(OrdersActivity.this, "");

                            }
                            LoadingDialogUtils.show(loadingDialog);
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread());


            HttpUtil.getInstance().toSubscribe(weChatPayOrder, new ProgressSubscriber<WeiChatPayBean>(this) {

                @Override
                protected void _onNext(StatusCode<WeiChatPayBean> weiChatPayBeanStatusCode) {
                    LoadingDialogUtils.closeDialog(loadingDialog);
                    WeiChatPayBean weiChatPayBean = weiChatPayBeanStatusCode.getData();
                    if (weiChatPayBeanStatusCode.isFlag() && weiChatPayBean != null) {


                  /*  PayReq req = new PayReq();
                    //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                    req.appId			= json.getString("appid");
                    req.partnerId		= json.getString("partnerid");
                    req.prepayId		= json.getString("prepayid");
                    req.nonceStr		= json.getString("noncestr");
                    req.timeStamp		= json.getString("timestamp");
                    req.packageValue	= json.getString("package");
                    req.sign			= json.getString("sign");
                    req.extData			= "app data"; // optional*/
/*                mIWXAPI.setLogImpl(new ILog() {
                    @Override
                    public void v(String s, String s1) {
                        LogUtils.v(TAG,"微信支付日志s ：：："+s);
                        LogUtils.v(TAG,"微信支付日志s1 ：：："+s1);
                    }

                    @Override
                    public void d(String s, String s1) {
                        LogUtils.d(TAG,"微信支付日志s ：：："+s);
                        LogUtils.d(TAG,"微信支付日志s1 ：：："+s1);
                    }

                    @Override
                    public void i(String s, String s1) {
                        LogUtils.i(TAG,"微信支付日志s ：：："+s);
                        LogUtils.i(TAG,"微信支付日志s1 ：：："+s1);
                    }

                    @Override
                    public void w(String s, String s1) {
                        LogUtils.w(TAG,"微信支付日志s ：：："+s);
                        LogUtils.w(TAG,"微信支付日志s1 ：：："+s1);
                    }

                    @Override
                    public void e(String s, String s1) {
                        LogUtils.e(TAG,"微信支付日志s ：：："+s);
                        LogUtils.e(TAG,"微信支付日志s1 ：：："+s1);
                    }
                });*/
                        PayReq req = new PayReq();
                        req.appId = weiChatPayBean.getAppid();
                        req.partnerId = weiChatPayBean.getPartnerid();
                        req.prepayId = weiChatPayBean.getPrepayid();
                        req.nonceStr = weiChatPayBean.getNoncestr();
                        req.timeStamp = weiChatPayBean.getTimestamp();
                        req.packageValue = weiChatPayBean.getPackageX();
                        req.sign = weiChatPayBean.getSign();
                        req.extData = WeChatPayType.FORM_HOUSE + "--" + roomId + "##" + mMoneyStr + "##" + mOrderBean.getOrderId() + "##" + payStyle;

                        if (req.checkArgs()) {
                            boolean b = mIWXAPI.sendReq(req);
                          //  ToastUtils.makeText("支付返回 ：：" + b + "——————————" + req.checkArgs());
                            LogUtils.i(TAG, "支付结果" + b);
                        } else {
                            LogUtils.i(TAG, "调起微信支付失败");
                        }


                    } else {
                        ToastUtils.makeText(weiChatPayBeanStatusCode.getDetailMsg() + "");
                    }
                }

                @Override
                protected void _onError(String message) {

                    LogUtils.i(TAG, message);
                    ToastUtils.makeText(message);
                    LoadingDialogUtils.closeDialog(loadingDialog);
                }

            }, "", lifecycleSubject, false, true);


        } else {
            Observable observable = ApiUtils.getApi().getAlipay(mOrderBean.getHousesId() + "", mMoneyStr, mOrderBean.getOrderId() + "", mOrderBean.getFullname(),type,BaseApplication.sUserInfoBean.userId,BaseApplication.sUserInfoBean.getToken())
                    .compose(RxHelper.getObservaleTransformer())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {

                            if (loadingDialog == null) {

                                loadingDialog = LoadingDialogUtils.createLoadingDialog(OrdersActivity.this, "");

                            }
                            LoadingDialogUtils.show(loadingDialog);
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread());

            HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<String>(OrdersActivity.this) {
                @Override
                protected void _onNext(StatusCode<String> stringStatusCode) {
                    LoadingDialogUtils.closeDialog(loadingDialog);
                    final String apyStr = stringStatusCode.getData();
                    LogUtils.i(TAG, "支付宝订单：" + apyStr);

                    if (stringStatusCode.isFlag() && !StringUtils.isEmpty(apyStr)) {

                        //成功
                        ThreadFactory.getNormalPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                //   AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
                                // Alipa

                                PayTask alipay = new PayTask(OrdersActivity.this);
                                Map<String, String> result = alipay.payV2(apyStr, true);
                                LogUtils.i(TAG, result.toString());
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);

                            }
                        });


                    } else {
                        ToastUtils.makeText(stringStatusCode.getDetailMsg());
                    }


                }

                @Override
                protected void _onError(String message) {
                    LoadingDialogUtils.closeDialog(loadingDialog);

                }
            }, "", lifecycleSubject, false, true);


        }
















 /*       if (isWeixinPay){
            //微信支付
        }else {
            //支付宝
        }
*/
        //

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     9000	订单支付成功
                     8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                     4000	订单支付失败
                     5000	重复请求
                     6001	用户中途取消
                     6002	网络连接出错
                     6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
                     其它	其它支付错误
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        // Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        ToastUtils.makeText("支付成功");
                        //跳成功页面
                        PayForSuccessActivity.startActivity(OrdersActivity.this, roomId + "##" + mMoneyStr + "##" + mOrderBean.getOrderId() + "##" + payStyle);
                        finish();

                    } else {

                        //失败
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        // Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        ToastUtils.makeText("支付失败");
                        finish();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (timeReduce!=null){
        timeReduce.setTimeControl(false);
        }
    }

    @OnClick(R.id.tv_anew_select_activity_orders)
    public void onTvAnewSelectOnClick(){
        finish();
    }


}
